package cn.bby.query.server.application.manager.impl;

import cn.bby.query.server.application.manager.SystemStatusManager;
import cn.bby.query.server.domain.agg.sys.repository.HealthInfoRepository;
import cn.bby.query.server.domain.share.constant.HealthInfoMetric;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author wangbenyin
 * @version 1.0
 * @date 2025/06/10
 * @since 17
 */
@Service
@RequiredArgsConstructor
public class SystemStatusManagerImpl implements SystemStatusManager {
    public static final List<String> HEART_BEAT_METRICS = List.of(HealthInfoMetric.CONSUMER.metric, HealthInfoMetric.LISTENER.metric);
    private final HealthInfoRepository healthInfoRepository;
    private final RedissonClient redissonClient;

    @PostConstruct
    public void init() {
        RLock lock = redissonClient.getLock("audit-query-heartbeat-lock-init");
        if (!lock.tryLock()) {
            return;
        }
        try {
            healthInfoRepository.initAndCreateBatch(List.of(HealthInfoMetric.CONSUMER, HealthInfoMetric.LISTENER));
        } finally {
            lock.unlock();
        }
    }

    @Override
    public void heartbeat(HealthInfoMetric metric) {
        healthInfoRepository.update(metric, System.currentTimeMillis());
    }

    @Override
    public boolean isHealth() {
        return healthInfoRepository.isHealth(HEART_BEAT_METRICS);
    }
}
